import { AudioSource } from "cc"
import { DataMgr } from "./DataMgr"
import { ResMgr } from "./ResMgr"
import { ENUM_AUDIO_CLIP } from "../Enum"

export class AudioMgr {
    private source: AudioSource = null
    private static _ins: any = null

    static getIns<T>(): T {
        if (this._ins === null) {
            this._ins = new this()
            this._ins.init()
        }

        return this._ins
    }

    static get ins() {
        return this.getIns<AudioMgr>()
    }

    init() {
        this.source = new AudioSource()
        this.source.loop = true
        this.source.volume = 0.3
    }

    async playMusic() {
        if (!DataMgr.ins.isMusic) return
        if (this.source.clip) {
            this.source.play()
            return
        }
        const clip = await ResMgr.ins.getAudio(ENUM_AUDIO_CLIP.BGM)
        this.source.clip = clip
        this.source.play()
    }

    stopMusic() {
        this.source.stop()
    }

    async playSound(name: ENUM_AUDIO_CLIP | string, isLoop: boolean = false) {
        if (!DataMgr.ins.isSound) return
        const clip = await ResMgr.ins.getAudio(name)
        this.source.playOneShot(clip)
    }
}


